package com.xebest.web.controller.restapi;

import com.alibaba.fastjson.JSONObject;
import com.xebest.api.dto.WeChatSevenDaysOrderCountDto;
import com.xebest.api.dto.WeChatSevenDaysOrderCountQueryDto;
import com.xebest.api.dto.WeChatSevenDaysOrderCountResonseDto;
import com.xebest.constant.XeErrorCode;
import com.xebest.util.DateUtil;
import com.xebest.util.Money;
import com.xebest.web.service.WeChatSevenDaysReadService;
import com.xebest.web.service.XeVenOrderService;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 微信ERP使用 查询7日销售额和订单数
 * @author chenjing
 */
@RestController
@RequestMapping("restapi/weChatSevenDays")
public class WeChatSevenDaysOrderCountRestApi {
    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(WeChatSevenDaysOrderCountRestApi.class);

    @Autowired
    private WeChatSevenDaysReadService readService;

    @Autowired
    private XeVenOrderService xeVenOrderService;
    /**
     * 查询7日订单数和销售额
     * @author chenjing
     */
    @RequestMapping("/orderCount")
    public WeChatSevenDaysOrderCountResonseDto querySevenDaysOrderCount(@RequestBody WeChatSevenDaysOrderCountQueryDto form){
        WeChatSevenDaysOrderCountResonseDto countResonseDto = new WeChatSevenDaysOrderCountResonseDto();
        List<WeChatSevenDaysOrderCountDto> orderCountList = new ArrayList<>();
        countResonseDto.setMsg("查询商户7日销售额和订单数");
        countResonseDto.setStatus(XeErrorCode.PORJECT_SUCCESS);
        String paramJson = JSONObject.toJSONString(form);
        log.info("查询商户7日销售额和订单数,传入参数： {}", paramJson);
        if(null == form || StringUtils.isBlank(form.getCreateDate())
                || StringUtils.isBlank(form.getUserCode()) || StringUtils.isBlank(form.getMonth())){
            countResonseDto.setMsg("缺少必要参数");
            countResonseDto.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
            return countResonseDto;
        }
        String createDate = form.getCreateDate();

        Map map = new HashedMap();
        map.put("userCode",form.getUserCode());
        map.put("paramValue",form.getMonth());
        try {
            //7日开始时间
            String createStartDate = DateUtil.getDateAdd(createDate,-6,14);
            //7日结束时间
            String createEndDate = createDate ;
            map.put("createStartDate",createStartDate);
            map.put("createEndDate",createEndDate);
            //获取7日内销售额和订单数
            List<Map<String,Object>> list = readService.querySevenDaysOrderCount(map);

            //每日销售额
            List<String> payAmount =  new ArrayList<>();
            // 订单数（每日）
            List<String> orderNum =  new ArrayList<>();
            // x轴  日期
            List<String> dateList =  new ArrayList<>();
            /**
             * 格式转换成前端需要的格式
             */
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            for(int i=6;i>=0;i--){
                String orderNumsByDay = "0";
                String totalAmount = "0";
                String formatDate = DateUtil.getDateAdd(createDate,-i,8);
                for (Map orderMap:list) {
                    if(orderMap.containsKey("createDate")&&orderMap.get("createDate").toString().trim().equals(formatDate)){
                        orderNumsByDay = orderMap.get("orderNum").toString();
                        totalAmount = Money.of(orderMap.get("totalAmount").toString()).divide(10000).toMoneyString();
                        break;
                    }
                }
                /**
                 * 填充柱状图数据
                 */
                dateList.add(formatDate);
                payAmount.add(totalAmount);
                orderNum.add(orderNumsByDay);
                /**
                 * 填充基本数据
                 */
                WeChatSevenDaysOrderCountDto orderCountDto = new WeChatSevenDaysOrderCountDto();
                orderCountDto.setCreateDate(formatDate);
                orderCountDto.setOrderNum(Integer.parseInt(orderNumsByDay));
                orderCountDto.setTotalAmount(new BigDecimal(totalAmount));
                orderCountList.add(orderCountDto);
            }
            countResonseDto.setDateList(dateList);
            countResonseDto.setOrderNum(orderNum);
            countResonseDto.setPayAmount(payAmount);
            countResonseDto.setOrderCountList(orderCountList);
        } catch (Exception e) {
            log.error("查询商户7日销售额和订单数接口异常：{}" , e);
            countResonseDto.setStatus(XeErrorCode.PORJECT_ERROR);
            countResonseDto.setMsg("查询商户7日销售额和订单数接口异常");
        }

        return countResonseDto;
    }

}
